<template>
  <el-upload :action="uploadAction" list-type="picture" :on-success="handleSuccess" :on-remove="handleRemove" :on-exceed="handleExceed" :file-list="fileList" :multiple="false" :limit="1">
    <el-button size="small" type="primary">点击上传</el-button>
    <template #tip>
      <div class="el-upload__tip">只能上传 1 个图标</div>
    </template>
  </el-upload>
</template>

<script>
import { reactive, toRefs, onRenderTracked } from 'vue'
import { ElMessage } from 'element-plus'
import config from '../../config'
export default {
  name: 'SingleUpload',
  props: {
    // 上传图标的接口地址
    uploadAction: {
      type: String,
      required: true
    },
    // 上传成功的回调函数
    successCallBack: {
      type: Function,
      required: true
    },
    // 编辑下，接收图标对象
    icon: {
      type: String
    }
  },
  setup(props, context) {
    const fileList = reactive([])
    // 删除
    const handleRemove = (file, fileList) => {
      // console.log(file, fileList)
      if (file.status === 'success') {
        props.successCallBack && props.successCallBack(null)
      }
    }

    // 上传成功
    const handleSuccess = (response, file, fileList) => {
      // console.log(response, file, fileList)
      if (response.status === 1) {
        // 存在successCallBack这个函数的时候才调用
        props.successCallBack && props.successCallBack(response.data)
      }
    }

    // 文件超出个数限制
    const handleExceed = () => {
      ElMessage({
        type: 'warning',
        message: '最多只能上传1个图标!',
        duration: 1000
      })
    }

    // 监听icon的值的变化
    onRenderTracked((event) => {
      if (props.icon) {
        fileList.push({
          name: props.icon.substring(props.icon.lastIndexOf('/') + 1), // 从最后一个斜杠开始截取，截到最后
          url: config.BASE_URL + props.icon
        })
      }
    })

    return {
      fileList,
      handleSuccess,
      handleRemove,
      handleExceed
    }
  }
}
</script>

<style>
</style>